#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>

//互斥锁
//临界资源，每次只能一个人使用
//比如上厕所，要获得锁才能写

//创建文件指针
FILE* pf;

//初始化互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

//线程1
void* func1(void* agr)
{
	int i;
	int c;
	pthread_detach(pthread_self());
	printf("线程1创建成功\n");
	//线程分离
	char str1[11] ="xiao yang\n";
	//写文件
	while(1)
	{
		i = 0;
		//获得锁
		pthread_mutex_lock(&mutex);
		for(i = 0; i < 11; i++)
		{
			c = str1[i];
			fputc(c, pf);
			usleep(1);
		}
		fclose(pf);
		//释放锁
		pthread_mutex_lock(&mutex);
		sleep(1);
	}

	pthread_exit(0);
}

//线程2
void* func2(void* agr)
{
	pthread_detach(pthread_self());
	int i;
	int c;
	printf("线程2创建成功\n");
	char str[]= "xiao huang\n";
	//获得锁
	while(1)
	{
		i = 0;
		pthread_mutex_lock(&mutex);
		for(i = 0; i < strlen(str); i++)
		{
			c = str[i];
			fputc(c, pf);
			usleep(1);
		}
		fclose(pf);
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}


	pthread_exit(0);

}



int main()
{

	pthread_t tid1;
	pthread_t tid2;
	int ret;

	//打开文件
	pf = fopen("1.data", "a+");
	if(pf == NULL)
	{
		perror("fopen");
		return -1;
	}

	//创建线程1和2
	ret = pthread_create(&tid1, NULL, func1, 1);
	ret = pthread_create(&tid2, NULL, func2, 2);

	//不结束主线程
	while(1)
	{
		sleep(1);
	}

}
























